package nl.boelen.game.server.connection;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import nl.boelen.game.server.gui.ServerGUI;

public class ServerTCPReceiver extends Thread {

    private ServerSocket socket;
    public boolean hasSocket = false;
    public ServerGUI serverGUI;
    private ServerPacketHandler packetHandler;

    public ServerTCPReceiver(ServerPacketHandler packetHandler) {
        this.packetHandler = packetHandler;

        try {
            this.socket = new ServerSocket(2222);
            this.hasSocket = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        String message = "";

        while (true) {
            try (Socket client = socket.accept()) {
                try (DataInputStream in = new DataInputStream(client.getInputStream())) {
                    try (DataOutputStream out = new DataOutputStream(client.getOutputStream())) {

                        int size = in.readInt();
                        byte[] data = new byte[size];
                        if (size > 0) {
                            in.readFully(data);

                            message = "OK";
                            out.writeInt(message.length());
                            out.write(message.getBytes());
                            out.flush();
                            
                            packetHandler.parsePacket(data, client.getInetAddress(), client.getPort());
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
